package org.simp.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.simp.common.Constants;

/**
 * 地址处理类
 * @Author zhuhaitao at 2014年6月7日
 *
 **/
public class AddressUtil {

	/**
	 * domain node1@server1@top
	 *	address client2@node2@server1@top
	 * 返回  client2@node2@server1@node1
	 * @param domain 域
	 * @param address 地址
	 * @return
	 * @Author zhuhaitao at 2014年6月7日
	 *
	 */
	public static String address(String domain,String address){
		if(StringUtils.isEmpty(domain) || StringUtils.isEmpty(address)){
			return address;
		}
		String equilsTemp = getEndEquals(domain, address);
		domain = domain.substring(0,domain.length() - equilsTemp.length());
		address = address.substring(0,address.length() - equilsTemp.length());
		
		if(StringUtil.isEmpty(domain)){
			address = address.substring(0,address.length() -1);
		}
		
		String serverNode ="";
		if(equilsTemp.contains(Constants.ADDRESS_SPLIT)){
			String[] arr = equilsTemp.split(Constants.ADDRESS_SPLIT);
			if(arr.length >=2){
				serverNode= arr[1];
			}
		}else{
			serverNode = equilsTemp;
		}
		
		if(address.endsWith(Constants.ADDRESS_SPLIT)){
			address +=  serverNode;
		}
//		else{
//			address += Constants.ADDRESS_SPLIT + serverNode;
//		}
		
		List<String> list = formatStringToList(domain);
		if(!list.isEmpty()){
			for(int i = list.size()-1;i>=0 ;i--){
				String s = list.get(i);
				if(StringUtils.isNotEmpty(s))
					address +=  Constants.ADDRESS_SPLIT +list.get(i) ;
			}
		}
		return address;
		
	}
	
	public static List<String> formatStringToList(String str){
		List<String> list = new ArrayList<String>();
		String[] arr = str.split(Constants.ADDRESS_SPLIT);
		for(String s : arr){
			list.add(s);
		}
		return list;
	}
	/**
	 * 返回两个字符串结尾相同的部分
	 * @param src
	 * @param dst
	 * @return
	 * @Author zhuhaitao at 2014年6月7日
	 *
	 */
	public static String getEndEquals(String src,String dst){
		int index =-1;
		for(int i=1;;i++){
			if(src.length() <= i || dst.length() <=i){
				index=i;
				break;
			}
			char a = src.charAt(src.length() -i);
			char b = dst.charAt(dst.length() -i);
			if(a != b){
				index = i -1;
				break;
			}
		}
		return src.substring(src.length() -index  ,src.length());
	}
}
